//
//  WRYBaseMenuViewController.m
//  BaiSiBuJie
//
//  Created by wry on 16/5/3.
//  Copyright © 2016年 WRY. All rights reserved.
//

#import "WRYBaseMenuViewController.h"
#import "WRYBaseThemeViewController.h"

static NSString *const ID=@"cell";

@interface WRYBaseMenuViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>

@property(nonatomic,weak)UIScrollView *topView;

@property(nonatomic,strong)NSMutableArray *titleButtons;

@property(nonatomic,weak)UICollectionView *contentView;
@property(nonatomic,weak)UIButton *preSelcetBtn;
@property(nonatomic,weak)UIView *underLine;
@property(nonatomic,assign)BOOL isInitial;//初始化



@end

@implementation WRYBaseMenuViewController

/**
 UITabBar: TabBar条
 UITabBarItem: 决定UITabBar的按钮内容
 UIBarButtonItem: 决定UINavigationBar的按钮内容
 UINavigationBar: 导航条
 UINavigationItem:决定导航条的内容,有几个按钮,左/右/标题.
 */

#pragma mark - 按钮数组懒加载
- (NSMutableArray *)titleButtons
{
    if (_titleButtons == nil) {
        _titleButtons = [NSMutableArray array];
    }
    return _titleButtons;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //iOS7之后，如果是导航控制器下scrollView,顶部都会添加64的额外滚动区域
    //the item height must be less than the height of the UICollectionView minus the section insets top and bottom values, minus the content insets top and bottom values. 因为在导航控制器下collectionView有额外的滚动区域
    //表示cell的尺寸 超过 UICollectionView尺寸UICollectionView尺寸 减去 顶部和底部额外间距
    
    self.automaticallyAdjustsScrollViewInsets=NO;
   
    //1.搭建底部view：UICollectionView
    [self setUpContentView];
    self.contentView.scrollsToTop=NO;

    // 2.搭建顶部view: UIScollowView //必须后添加,否则会被盖住
    [self setUpTopView];
    self.topView.scrollsToTop=NO;

}


-(void)viewWillAppear:(BOOL)animated//在这里写添加标题,子类设置标题时才不会出错
{
    [super viewWillAppear:animated];
    
    // dispatch_once:整个app运行过程中 只会执行一次
    // 3.设置所有标题按钮
    if (_isInitial==NO) {//没有初始化就添加按钮,已经初始化不添加按钮
        [self setUpTitleBtn];
        _isInitial=YES;
    }
}

#pragma mark - 添加所有标题按钮
-(void)setUpTitleBtn
{
    NSInteger count=self.childViewControllers.count;
    
    CGFloat x=0;
    CGFloat y=0;
    CGFloat w=self.topView.width/count;
    CGFloat h=self.topView.height;
    for (int i=0; i<count; i++) {
        UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
        NSString *title=[self.childViewControllers[i] title];
        
        [btn setTitle:title forState:UIControlStateNormal];
        
        [btn setTitleColor:[UIColor redColor] forState:(UIControlStateSelected)];
        
        [btn setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
        
        
        x=i*w;
        btn.frame=CGRectMake(x, y, w, h);
        btn.tag=i;
        
        btn.titleLabel.font=[UIFont systemFontOfSize:14];
        
        [btn addTarget:self action:@selector(buttonClick:) forControlEvents:(UIControlEventTouchDown)];
        
        [_topView  addSubview:btn];
        //加到数组里面
        [self.titleButtons  addObject:btn];//用点语法,才会调用set,get方法
        
        // 默认选中第0个按钮
        if (i==0) {
            [self buttonClick:btn];
            //在这里创建下划线,注意:不显示下划线的原因:按钮的标题的宽度不会马上计算;只能手动计算文字的宽度
            UIView *underLine=[[UIView alloc]init];
            
            _underLine=underLine;
            
            //宽度
            underLine.width=[title sizeWithFont:[UIFont systemFontOfSize:14]].width;
            //中心点x  :先确定尺寸再确定位置
            underLine.centerX=btn.centerX;
            //y
            underLine.y=_topView.height-2;
            
            //高度
            underLine.height=2;
            
            underLine.backgroundColor=[UIColor redColor];
            //下划线加到topView上
            [_topView addSubview:underLine];
        }
    }
}


#pragma mark - 点击标题按钮
-(void)buttonClick:(UIButton *)btn
{
    NSInteger i =btn.tag;
    if (btn==_preSelcetBtn) { //重复点击标题按钮就下拉刷新
        //刷新对应子控制器数据
        WRYBaseThemeViewController *vc=self.childViewControllers[i];
        [vc reloadData];
    }

    //选中按钮
    [self selectBtn:btn];
    
    //让collectionView滚动到对应位置,并不是马上滚动,有延时
    CGFloat offsetX=WRYScreenW*i;
    _contentView.contentOffset=CGPointMake(offsetX, 0);
    
}
-(void)selectBtn:(UIButton *)btn
{
    _preSelcetBtn.selected=NO;
    btn.selected=YES;
    _preSelcetBtn=btn;
    _underLine.centerX=btn.centerX;
    
}

#pragma mark - 添加topView
-(void)setUpTopView{
    CGFloat topViewX=0;
    CGFloat topViewY=0;
    CGFloat topViewW=WRYScreenW;
    CGFloat const topViewH=44;
    
    if(self.navigationController.navigationBarHidden){
        topViewY=20;
    }else {topViewY=64;}
    
    UIScrollView *topView=[[UIScrollView alloc]initWithFrame:CGRectMake(topViewX, topViewY, topViewW, topViewH)];
    topView.showsHorizontalScrollIndicator=NO;
    
    _topView=topView;
    
    //添加topView
    [self.view addSubview:topView];
    
}


#pragma mark - 添加ContentView
-(void)setUpContentView

{
    // 搭建底部view：UICollectionView；占据全屏
    // 不管一个view当前有没有显示出来，只要添加到屏幕上就会被渲染
    // UICollectionView做的优化，并不是少创建控制器的view，而是对控制器的view的渲染进行优化
    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc]init];
    layout.itemSize=self.view.frame.size;
    layout.minimumLineSpacing=0;
    layout.minimumInteritemSpacing=0;
    layout.scrollDirection=UICollectionViewScrollDirectionHorizontal;
    
    UICollectionView *contentView=[[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:layout];
    _contentView=contentView;
    
    // 指示器，cell间距，分页
    contentView.pagingEnabled=YES;
    contentView.showsHorizontalScrollIndicator=NO;
    // 数据源代理
    contentView.dataSource=self;
    contentView.delegate=self;
    //额外滚动区域
    
    [self.view addSubview:contentView];
    
    // 注册cell
    [contentView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:ID];
}

#pragma mark - UICollectionViewDataSource

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.childViewControllers.count;
}
// 只要有新的cell显示的时候才会调用
// 返回cell
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    
    UIViewController *vc=self.childViewControllers[indexPath.row];
    
    //保证添加一个在屏幕上,才能只渲染一个,移除其余的子控件
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    // 3.把对应子控制器的view添加到对应的cell 的 contentView
    // 注意:一定要记得设置子控制器的view尺寸和位置 ,否则会有默认20的下移
    vc.view.frame=CGRectMake(0, 0, WRYScreenW, WRYScreenH);
    [cell.contentView addSubview:vc.view];
    
    return cell;
}

#pragma mark - 滚动完成
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    //页码
    NSInteger i = scrollView.contentOffset.x / WRYScreenW;
    // 选中对应的标题
    [self selectBtn:self.titleButtons[i]];
}



@end
